package smashedapples.stocktwits
{
	import com.adobe.serialization.json.JSON;
	
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	import mx.events.FlexEvent;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.mxml.HTTPService;
	
	import smashedapples.core.NonVisualComponent;
	import smashedapples.utils.ValueObjectUtils;
	
	[Event(name="resultsChanged",type="AppEvent")]
	
	
	public class StockTwitsApi extends NonVisualComponent
	{
		
		public static const STOCKTWITS_JSON_URL:String = "http://stocktwits.com/streams/all.json";
		
		public var timer:Timer;
		
		public var timerDelay:Number = 600000;
		
		[Bindable]
		public var result:ArrayCollection = new ArrayCollection();
		
		public function StockTwitsApi()
		{
			super();
			
			this.addEventListener( FlexEvent.CREATION_COMPLETE, handleCreationComplete );
		}
		
		protected function handleCreationComplete( event:FlexEvent ):void
		{
			this.setupTimer();
		}
		
		private function setupTimer( event:TimerEvent = null ):void
		{
			if( this.timer != null )
				this.timer.stop();
						
			this.timer = new Timer( this.timerDelay, 1 );
			this.timer.addEventListener( TimerEvent.TIMER_COMPLETE, setupTimer );
			this.timer.start();
			
			this.getStockTwits();
		}
		
		public function getStockTwits():void
		{
			var service:HTTPService = new HTTPService();
				service.url = STOCKTWITS_JSON_URL;
				service.resultFormat = "text";
				service.addEventListener(ResultEvent.RESULT, handleGetStockTwitsResult );
				service.addEventListener(FaultEvent.FAULT, handleGetStockTwitsFault );
				service.send();
		}
		
		
		protected function handleGetStockTwitsResult( event:ResultEvent ):void
		{
			var o:Object = JSON.decode( String( event.result ) );
			var a:Array =  o["stream"]["tweets"] as Array;
			this.result = new ArrayCollection( ValueObjectUtils.typeArray( a, StockTwitVO ) );
			
			this.dispatchEvent( new AppEvent( "resultsChanged" ));
		}
		
		protected function handleGetStockTwitsFault( event:FaultEvent ):void
		{
			trace(event.fault);
		}
		
		
		
	}
}